<template>
  <div class="page-container">
    <h1 class="metro-title"><i class="metro-icon"></i>地铁站点管理</h1>
    <div id="mapView" class="map-view">
      <!-- 图层控制面板 -->
      <div class="layer-control-panel">
        <el-card class="layer-card">
          <el-collapse v-model="activeCollapse">
            <el-collapse-item title="图层显示控制" name="layers">
              <el-space direction="vertical" alignment="stretch" size="small">
                <el-checkbox
                  v-model="layerVisibility.subwayLine"
                  @change="toggleLayerVisibility('subwayLine')"
                  class="metro-checkbox"
                  >地铁线路</el-checkbox
                >
                <el-checkbox
                  v-model="layerVisibility.subwayStation"
                  @change="toggleLayerVisibility('subwayStation')"
                  class="metro-checkbox"
                  >地铁站点</el-checkbox
                >
              </el-space>
            </el-collapse-item>
            <el-collapse-item title="图层操作控制" name="operations">
              <el-space direction="vertical" alignment="stretch" size="small">
                <el-button type="primary" @click="startAddStation" class="metro-button">
                  <el-icon><Plus /></el-icon> 新增地铁站点
                </el-button>
              </el-space>
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </div>

      <!-- 站点属性表单对话框 -->
      <el-dialog
        v-model="stationFormVisible"
        :title="formMode === 'add' ? '新增地铁站点' : '编辑地铁站点'"
        width="500px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <el-form
          :model="stationForm"
          label-width="120px"
          :rules="stationFormRules"
          ref="stationFormRef"
        >
          <el-form-item label="站点名称" prop="StationName">
            <el-input v-model="stationForm.StationName" placeholder="请输入站点名称"></el-input>
          </el-form-item>
          <el-form-item label="站点编码" prop="StationCode">
            <el-input v-model="stationForm.StationCode" placeholder="请输入站点编码"></el-input>
          </el-form-item>
          <el-form-item label="开通日期" prop="OpenDate">
            <el-date-picker
              v-model="stationForm.OpenDate"
              type="date"
              placeholder="请选择开通日期"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="运营状态" prop="Status">
            <el-select
              v-model="stationForm.Status"
              placeholder="请选择运营状态"
              style="width: 100%"
            >
              <el-option label="运营中" value="运营中"></el-option>
              <el-option label="在建" value="在建"></el-option>
              <el-option label="规划中" value="规划中"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="详细地址" prop="Address">
            <el-input v-model="stationForm.Address" placeholder="请输入详细地址"></el-input>
          </el-form-item>
          <el-form-item label="站点类型" prop="StationType">
            <el-select
              v-model="stationForm.StationType"
              placeholder="请选择站点类型"
              style="width: 100%"
            >
              <el-option label="普通站" value="普通站"></el-option>
              <el-option label="换乘站" value="换乘站"></el-option>
              <el-option label="终点站" value="终点站"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="换乘线路" prop="TransferLines">
            <el-select
              v-model="stationForm.TransferLines"
              multiple
              placeholder="请选择换乘线路"
              style="width: 100%"
            >
              <el-option
                v-for="line in subwayLines"
                :key="line.attributes.OBJECTID"
                :label="line.attributes.LineName"
                :value="line.attributes.LineName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="出口数量" prop="ExitCount">
            <el-input-number
              v-model="stationForm.ExitCount"
              :min="1"
              :max="20"
              placeholder="请输入出口数量"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="日均客流量" prop="DailyPassengers">
            <el-input-number
              v-model="stationForm.DailyPassengers"
              :min="0"
              :step="1000"
              placeholder="请输入日均客流量"
            ></el-input-number>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancelStationForm">取消</el-button>
            <el-button type="primary" @click="submitStationForm">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 站点属性查看对话框 -->
      <el-dialog
        v-model="stationInfoVisible"
        title="地铁站点信息"
        width="500px"
        :key="refreshStationKey"
      >
        <div v-if="selectedStation">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="站点名称">{{
              selectedStation.attributes.StationName
            }}</el-descriptions-item>
            <el-descriptions-item label="站点编码">{{
              selectedStation.attributes.StationCode
            }}</el-descriptions-item>
            <el-descriptions-item label="开通日期">{{
              selectedStation.attributes.OpenDate
            }}</el-descriptions-item>
            <el-descriptions-item label="运营状态">{{
              selectedStation.attributes.Status
            }}</el-descriptions-item>
            <el-descriptions-item label="详细地址">{{
              selectedStation.attributes.Address
            }}</el-descriptions-item>
            <el-descriptions-item label="站点类型">{{
              selectedStation.attributes.StationType
            }}</el-descriptions-item>
            <el-descriptions-item label="换乘线路">{{
              selectedStation.attributes.TransferLines
            }}</el-descriptions-item>
            <el-descriptions-item label="出口数量">{{
              selectedStation.attributes.ExitCount
            }}</el-descriptions-item>
            <el-descriptions-item label="日均客流量">{{
              selectedStation.attributes.DailyPassengers
            }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="stationInfoVisible = false">关闭</el-button>
            <el-button type="primary" @click="editStation">编辑</el-button>
            <el-button type="danger" @click="confirmDeleteStation">删除</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 删除确认对话框 -->
      <el-dialog v-model="deleteConfirmVisible" title="确认删除" width="300px">
        <p>确定要删除该地铁站点吗？此操作不可恢复。</p>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deleteConfirmVisible = false">取消</el-button>
            <el-button type="danger" @click="deleteStation">确定删除</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, reactive, nextTick } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Graphic from '@arcgis/core/Graphic.js'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer.js'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol.js'
import Query from '@arcgis/core/rest/support/Query.js'
import gaodeLayer from '../../utils/GaoDeBaseLayer'
import PopupTemplate from '@arcgis/core/PopupTemplate.js'

type StationFormType = {
  StationName: string
  StationCode: string
  OpenDate: string
  Status: string
  Address: string
  StationType: string
  TransferLines: string[]
  ExitCount: number
  DailyPassengers: number
}

let view: MapView | null = null
let subwayLineLayer: FeatureLayer | null = null
let subwayStationLayer: FeatureLayer | null = null
let sketchLayer: GraphicsLayer | null = null
let tempGraphic: Graphic | null = null

// 图层可见性控制
const layerVisibility = ref({
  subwayLine: true,
  subwayStation: true,
})

// 控制折叠面板的展开状态
const activeCollapse = ref(['layers', 'operations'])
// 添加一个刷新标记
const refreshStationKey = ref(0)

// 表单相关
const stationFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const stationFormVisible = ref(false)
const formMode = ref<'add' | 'edit'>('add')
const stationInfoVisible = ref(false)
const deleteConfirmVisible = ref(false)
let selectedStation: Graphic | null = null

// 线路列表
let subwayLines: Graphic[] = []

// 站点表单数据
const stationForm = reactive<StationFormType>({
  StationName: '',
  StationCode: '',
  OpenDate: '',
  Status: '运营中',
  Address: '',
  StationType: '普通站',
  TransferLines: [],
  ExitCount: 1,
  DailyPassengers: 0,
})

// 站点表单验证规则
const stationFormRules = {
  StationName: [{ required: true, message: '请输入站点名称', trigger: 'blur' }],
  StationCode: [{ required: true, message: '请输入站点编码', trigger: 'blur' }],
  OpenDate: [{ required: true, message: '请选择开通日期', trigger: 'blur' }],
  Status: [{ required: true, message: '请选择运营状态', trigger: 'blur' }],
  Address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  StationType: [{ required: true, message: '请选择站点类型', trigger: 'blur' }],
  ExitCount: [{ required: true, message: '请输入出口数量', trigger: 'blur' }],
  DailyPassengers: [{ required: true, message: '请输入日均客流量', trigger: 'blur' }],
}

// 切换图层可见性
const toggleLayerVisibility = (layerType: string) => {
  switch (layerType) {
    case 'subwayLine':
      if (subwayLineLayer) {
        subwayLineLayer.visible = Boolean(layerVisibility.value.subwayLine)
      }
      break
    case 'subwayStation':
      if (subwayStationLayer) {
        subwayStationLayer.visible = Boolean(layerVisibility.value.subwayStation)
      }
      break
  }
}

// 开始添加地铁站点
const startAddStation = () => {
  if (!view) return

  // 监听地图点击事件，用于选择站点位置
  const clickHandler = view.on('click', (event) => {
    // 创建临时图形
    tempGraphic = new Graphic({
      geometry: event.mapPoint,
      symbol: new SimpleMarkerSymbol({
        color: [0, 0, 255, 0.8],
        size: 12,
        outline: {
          color: [255, 255, 255],
          width: 1,
        },
      }),
    })

    // 添加到草图图层
    if (sketchLayer) {
      sketchLayer.removeAll() // 清除之前的点
      sketchLayer.add(tempGraphic)
    }

    // 显示表单
    formMode.value = 'add'
    stationFormVisible.value = true

    // 移除点击事件监听
    clickHandler.remove()
  })

  ElMessage.info('请在地图上点击选择站点位置')
}

// 取消站点表单
const cancelStationForm = () => {
  stationFormVisible.value = false
  resetStationForm()

  // 如果是添加模式，清除临时图形
  if (formMode.value === 'add' && tempGraphic && sketchLayer) {
    sketchLayer.remove(tempGraphic)
    tempGraphic = null
  }
}

// 重置站点表单
const resetStationForm = () => {
  if (stationFormRef.value) {
    stationFormRef.value.resetFields()
  }

  stationForm.StationName = ''
  stationForm.StationCode = ''
  stationForm.OpenDate = ''
  stationForm.Status = '运营中'
  stationForm.Address = ''
  stationForm.StationType = '普通站'
  stationForm.TransferLines = []
  stationForm.ExitCount = 1
  stationForm.DailyPassengers = 0
}

// 提交站点表单
const submitStationForm = async () => {
  if (!stationFormRef.value) return

  await stationFormRef.value.validate(async (valid) => {
    if (valid) {
      if (formMode.value === 'add') {
        // 添加新站点
        addStation()
      } else {
        // 更新站点
        updateStation()
      }
    }
  })
}

// 添加新站点
const addStation = () => {
  if (!tempGraphic || !subwayStationLayer) return

  // 处理换乘线路数组为字符串
  const transferLinesStr = stationForm.TransferLines.join(',')

  // 创建新的站点图形
  const attributes = {
    StationName: stationForm.StationName,
    StationCode: stationForm.StationCode,
    OpenDate: stationForm.OpenDate,
    Status: stationForm.Status,
    Address: stationForm.Address,
    StationType: stationForm.StationType,
    TransferLines: transferLinesStr,
    ExitCount: stationForm.ExitCount,
    DailyPassengers: stationForm.DailyPassengers,
  }

  // 创建新的图形
  const newGraphic = new Graphic({
    geometry: tempGraphic.geometry,
    attributes: attributes,
  })

  // 添加到图层
  subwayStationLayer
    .applyEdits({
      addFeatures: [newGraphic],
    })
    .then((result) => {
      if (result.addFeatureResults.length > 0) {
        ElMessage.success('地铁站点添加成功')
        stationFormVisible.value = false
        resetStationForm()

        // 清除临时图形
        if (sketchLayer && tempGraphic) {
          sketchLayer.remove(tempGraphic)
          tempGraphic = null
        }
      } else {
        ElMessage.error('地铁站点添加失败')
      }
    })
    .catch((error) => {
      console.error('添加地铁站点出错:', error)
      ElMessage.error('地铁站点添加失败')
    })
}

// 编辑站点
const editStation = () => {
  if (!selectedStation) return

  formMode.value = 'edit'

  // 填充表单数据
  const attrs = selectedStation.attributes
  stationForm.StationName = attrs.StationName || ''
  stationForm.StationCode = attrs.StationCode || ''
  stationForm.OpenDate = attrs.OpenDate || ''
  stationForm.Status = attrs.Status || '运营中'
  stationForm.Address = attrs.Address || ''
  stationForm.StationType = attrs.StationType || '普通站'

  // 处理换乘线路字符串为数组
  if (attrs.TransferLines) {
    stationForm.TransferLines = attrs.TransferLines.split(',')
  } else {
    stationForm.TransferLines = []
  }

  stationForm.ExitCount = attrs.ExitCount || 1
  stationForm.DailyPassengers = attrs.DailyPassengers || 0

  stationInfoVisible.value = false
  stationFormVisible.value = true
}

// 更新站点
const updateStation = () => {
  if (!selectedStation || !subwayStationLayer) return

  // 处理换乘线路数组为字符串
  const transferLinesStr = stationForm.TransferLines.join(',')

  // 更新属性
  const updatedGraphic = selectedStation.clone()
  updatedGraphic.attributes.StationName = stationForm.StationName
  updatedGraphic.attributes.StationCode = stationForm.StationCode
  updatedGraphic.attributes.OpenDate = stationForm.OpenDate
  updatedGraphic.attributes.Status = stationForm.Status
  updatedGraphic.attributes.Address = stationForm.Address
  updatedGraphic.attributes.StationType = stationForm.StationType
  updatedGraphic.attributes.TransferLines = transferLinesStr
  updatedGraphic.attributes.ExitCount = stationForm.ExitCount
  updatedGraphic.attributes.DailyPassengers = stationForm.DailyPassengers

  // 应用编辑
  subwayStationLayer
    .applyEdits({
      updateFeatures: [updatedGraphic],
    })
    .then((result) => {
      if (result.updateFeatureResults.length > 0) {
        ElMessage.success('地铁站点更新成功')
        stationFormVisible.value = false
        resetStationForm()
        // 强制刷新组件
        nextTick(() => {
          refreshStationKey.value++
        })
      } else {
        ElMessage.error('地铁站点更新失败')
      }
    })
    .catch((error) => {
      console.error('更新地铁站点出错:', error)
      ElMessage.error('地铁站点更新失败')
    })
}

// 确认删除站点
const confirmDeleteStation = () => {
  stationInfoVisible.value = false
  deleteConfirmVisible.value = true
}

// 删除站点
const deleteStation = () => {
  if (!selectedStation || !subwayStationLayer) return

  subwayStationLayer
    .applyEdits({
      deleteFeatures: [selectedStation],
    })
    .then((result) => {
      if (result.deleteFeatureResults.length > 0) {
        ElMessage.success('地铁站点删除成功')
        deleteConfirmVisible.value = false
      } else {
        ElMessage.error('地铁站点删除失败')
      }
    })
    .catch((error) => {
      console.error('删除地铁站点出错:', error)
      ElMessage.error('地铁站点删除失败')
    })
}

// 加载地铁线路列表
const loadSubwayLines = () => {
  if (!subwayLineLayer) {
    ElMessage.warning('线路图层未加载')
    return
  }

  // 查询所有线路
  const query = subwayLineLayer.createQuery()
  query.outFields = ['*']
  query.returnGeometry = false

  subwayLineLayer
    .queryFeatures(query)
    .then((results) => {
      if (results.features && results.features.length > 0) {
        subwayLines = results.features
      }
    })
    .catch((error) => {
      console.error('加载线路列表出错:', error)
      ElMessage.error('加载线路列表失败')
    })
}

// 初始化地图
onMounted(() => {
  // 创建地铁线路图层
  subwayLineLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/WAsbhBMtbJ0DBeIA/arcgis/rest/services/地铁站点/FeatureServer/1',
    title: '地铁线路',
    visible: Boolean(layerVisibility.value.subwayLine),
    outFields: ['*'], // 确保所有字段都可用
    popupEnabled: true, // 启用默认弹出窗口
    popupTemplate: new PopupTemplate({
      title: '{LineName}',
      content: [
        {
          type: 'fields',
          fieldInfos: [
            { fieldName: 'LineNumber', label: '线路编号' },
            { fieldName: 'StationCount', label: '站点数量' },
            { fieldName: 'FirstTrainTime', label: '首班车时间' },
            { fieldName: 'LastTrainTime', label: '末班车时间' },
            { fieldName: 'TrackType', label: '轨道类型' },
            { fieldName: 'DailyPassengers', label: '日均客流量' },
          ],
        },
      ],
    }),
  })

  // 创建地铁站点图层
  subwayStationLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/WAsbhBMtbJ0DBeIA/arcgis/rest/services/地铁站点/FeatureServer/0',
    title: '地铁站点',
    visible: Boolean(layerVisibility.value.subwayStation),
    outFields: ['*'],
    popupEnabled: false, // 禁用默认弹出窗口，使用自定义弹窗
  })

  // 创建草图图层
  sketchLayer = new GraphicsLayer({
    title: '草图图层',
  })

  // 创建地图实例
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
    layers: [subwayLineLayer, subwayStationLayer, sketchLayer], // 添加图层到地图
  })

  // 创建地图视图
  view = new MapView({
    container: 'mapView',
    map: map,
    zoom: 10,
    center: [116.397428, 39.90923], // 默认中心点（北京）
  })

  // 加载线路列表
  loadSubwayLines()

  // 监听点击事件，用于查询要素信息
  view.on('click', async function (event) {
    // 如果正在添加站点，则不处理点击事件
    if (stationFormVisible.value) return

    // 转换空间参考
    const mapPoint = event.mapPoint
    // 创建查询对象
    const query = new Query()
    query.geometry = mapPoint
    query.distance = 1 // 增加点击容差
    query.units = 'kilometers'
    query.spatialRelationship = 'intersects'
    query.returnGeometry = true
    query.outFields = ['*']

    try {
      // 查询地铁站点图层
      if (subwayStationLayer && subwayStationLayer.visible) {
        const stationResult = await subwayStationLayer.queryFeatures(query)
        if (stationResult.features.length > 0) {
          // 找到站点，显示信息
          selectedStation = stationResult.features[0]
          stationInfoVisible.value = true
          nextTick(() => {
            refreshStationKey.value++
          })
          return
        }
      }
    } catch (error) {
      console.error('查询要素出错:', error)
      ElMessage.error('查询要素失败')
    }
  })
})

// 组件卸载时清理资源
onUnmounted(() => {
  if (view) {
    view = null
  }
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  height: calc(100vh - 140px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.metro-title {
  margin-bottom: 20px;
  color: #0052cc;
  font-size: 28px;
  font-weight: 600;
  display: flex;
  align-items: center;
  position: relative;
  padding-left: 40px;
  letter-spacing: 1px;
}

.metro-title::before {
  content: '';
  position: absolute;
  left: 0;
  width: 30px;
  height: 30px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%230052cc"><path d="M12,2C8.13,2,5,5.13,5,9c0,5.25,7,13,7,13s7-7.75,7-13C19,5.13,15.87,2,12,2z M12,11.5c-1.38,0-2.5-1.12-2.5-2.5s1.12-2.5,2.5-2.5s2.5,1.12,2.5,2.5S13.38,11.5,12,11.5z"/></svg>');
  background-repeat: no-repeat;
  background-size: contain;
}

.map-view {
  width: 100%;
  height: 100%;
  position: relative;
  flex-grow: 1;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.1);
}

.layer-control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
  width: 280px;
}

.layer-card {
  background-color: rgba(255, 255, 255, 0.92);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: none;
  overflow: hidden;
}

.layer-card :deep(.el-collapse) {
  border: none;
}

.layer-card :deep(.el-collapse-item__header) {
  font-weight: 600;
  color: #0052cc;
  background-color: rgba(240, 245, 255, 0.9);
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 8px;
}

.layer-card :deep(.el-collapse-item__content) {
  padding: 12px 16px;
}

.metro-checkbox {
  margin: 4px 0;
}

.metro-checkbox :deep(.el-checkbox__label) {
  color: #606266;
  font-size: 14px;
}

.metro-button {
  width: 100%;
  margin-top: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.el-descriptions {
  margin-top: 16px;
}

.el-descriptions-item {
  padding: 8px 0;
}

.el-descriptions-item__label {
  font-weight: 500;
  color: #606266;
}

.el-descriptions-item__content {
  color: #303133;
}

@media (max-width: 768px) {
  .layer-control-panel {
    width: 240px;
    top: 10px;
    right: 10px;
  }

  .metro-title {
    font-size: 24px;
    padding-left: 36px;
  }
}
</style>
